import { FC } from "react";
import { Button, Card, Dropdown, Menu, Tabs } from "@arco-design/web-react";
import { useLocation } from "react-router-dom";
import { css } from "@emotion/css";
import { IconPlusCircle } from "@arco-design/web-react/icon";
import { useConfigRoute } from "../../hooks/useConfigRoute.ts";
import { atomWithStorage } from "jotai/utils";
import { atom, useAtom, useSetAtom } from "jotai";
import { RouteData } from "../../api/types/routes.ts";
import { v4 as uuid } from "uuid";

export interface WorkspaceTab {
  name: string;
  path: string;
  key: string;
}

export const DEFAULT_TAB = {
  name: "工作台",
  path: "/homepage/index",
  key: "init",
};

export const workspaceTabsAtom = atomWithStorage<WorkspaceTab[]>(
  "workspace-tabs",
  [DEFAULT_TAB],
  undefined,
  {
    getOnInit: true,
  },
);

export const activeTabKeyAtom = atomWithStorage(
  "workspace-active-tabs",
  DEFAULT_TAB.key,
  undefined,
  {
    getOnInit: true,
  },
);

export function useResetWorkspaceTabs() {
  const setWorkspaceTabs = useSetAtom(workspaceTabsAtom);
  const setActiveTab = useSetAtom(activeTabKeyAtom);
  return () => {
    setWorkspaceTabs([DEFAULT_TAB]);
    setActiveTab(DEFAULT_TAB.key);
  };
}

export const activeTabAtom = atom((get) => {
  const tabs = get(workspaceTabsAtom);
  const activeTabKey = get(activeTabKeyAtom);
  return tabs.find((tab) => tab.key === activeTabKey);
});

export const WorkspaceTabs: FC = () => {
  const [tabs, setTabs] = useAtom(workspaceTabsAtom);
  const [activeTabKey, setActiveTabKey] = useAtom(activeTabKeyAtom);
  const { pathname } = useLocation();

  const handleAddTab = (route: RouteData) => {
    const newTab: WorkspaceTab = {
      name: route.meta.title,
      path: route.path,
      key: uuid(),
    };
    setTabs([...tabs, newTab]);

    setActiveTabKey(newTab.key);
  };

  const handleDeleteTab = (key: string) => {
    const index = tabs.findIndex((x) => x.key === key);
    const newTabs = tabs.slice(0, index).concat(tabs.slice(index + 1));

    if (key === activeTabKey && index > -1 && newTabs.length) {
      setActiveTabKey(
        newTabs[index] ? newTabs[index].key : newTabs[index - 1].key,
      );
    }

    if (index > -1) {
      setTabs(newTabs);
    }
  };
  const { data: routes } = useConfigRoute();

  if (pathname !== "/homepage/index") {
    return null;
  }

  return (
    <Card
      className={css`
        border-radius: 4px;
        margin: 20px 24px -40px 24px;
        > .arco-card-body {
          padding: 20px;
        }
      `}
      bordered={false}
    >
      <Tabs
        editable={tabs.length > 0}
        type="card-gutter"
        activeTab={activeTabKey}
        addButton={
          <Dropdown
            trigger="click"
            droplist={
              <Menu>
                {routes?.data
                  ?.flatMap((route) =>
                    route.children?.map((subRoute) => {
                      if (route.alwaysShow === false || route.hidden) {
                        return null;
                      }
                      return {
                        ...subRoute,
                        path: `${route.path}/${subRoute.path}`,
                      };
                    }),
                  )
                  .filter((x) => x)
                  .map((route) => {
                    return (
                      <Menu.Item
                        key={route!.path}
                        data-path={route!.path}
                        onClick={(e) => {
                          e.stopPropagation();
                          handleAddTab(route!);
                        }}
                      >
                        {route!.meta.title}
                      </Menu.Item>
                    );
                  })}
              </Menu>
            }
          >
            <Button
              type="text"
              onClick={(e) => e.stopPropagation()}
              iconOnly
              icon={<IconPlusCircle />}
            />
          </Dropdown>
        }
        onDeleteTab={handleDeleteTab}
        onChange={setActiveTabKey}
      >
        {tabs.map((tab) => (
          <Tabs.TabPane destroyOnHide key={tab.key} title={tab.name} />
        ))}
      </Tabs>
    </Card>
  );
};
